import loginService from '../../service/login.service'
const app = getApp()

Page({

  data: {

  },

  onLoad() {
    this.userLogin()
  },

  onShow() {
  },

  /*
  * 获取授权码
  */
  getAuthCode(cb) {
    dd.getAuthCode({
      success: (res) => {
        app.globalData.authCode = res.authCode
        cb && cb()
      },
      fail: (error) => {
        app.setDefGlobalData()
        dd.showToast({
          type: 'fail',
          content: '授权码获取失败'
        })
      }
    })
  },

  /**
   * 登录
   */
  userLogin() {
    this.getAuthCode(() => {
      let params = {
        authCode: app.globalData.authCode
      }

      let success = function (res) {
        console.log('getAuthCode', res)
        res.data.result['ranking'] = 0
        res.data.result['level'] = 1
        app.globalData.userInfo.id = res.data.result.id // 用户id
        app.globalData.userInfo.userId = res.data.result.dingTalkUserId // 钉钉id
        app.globalData.userInfo.tenantId = res.data.result.tenantId // 租户id
        app.globalData.userInfo.userName = res.data.result.userName
        app.globalData.userInfo.role = res.data.result.roleCode
        app.globalData.userInfo.roleDic = res.data.result.roleDic
        app.globalData.userInfo.score = res.data.result.integral
        app.globalData.userInfo.ranking = res.data.result.ranking
        app.globalData.userInfo.level = res.data.result.level
        app.globalData.userInfo.image = res.data.result.logo

        app.globalData.isLogin = true
        app.globalData.serverTime = getNewDate()
        console.log('app.globalData', app.globalData)

        dd.reLaunch({ url: '/page/index/index' })
      }

      let fail = function (msg) {

        app.setDefGlobalData()
        dd.showToast({
          type: 'fail',
          content: msg
        })
      }

      loginService.login(params, success, fail)
    })
  }
})

function getNewDate() {
    var date = new Date();
    console.log(date);
    var transverse = "-";
    var Verticalpoint = ":";
    var month = date.getMonth() + 1;//获取月份
    var strDate = date.getDate();//获取具体的日期           
    var strHour = date.getHours();//获取...钟点
    var strMinute = date.getMinutes();//获取分钟数
    var strSeconde = date.getSeconds();//获取秒钟数
    //判断获取月份 、 具体的日期 、...钟点、分钟数、秒钟数 是否在1~9
    //如果是则在前面加“0”
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 1 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if (strHour >= 1 && strHour <=9) {
        strHour = "0" + strHour
    }
    if (strMinute >= 1 && strMinute <= 9) {
        strMinute = "0" + strMinute;
    }

    if (strSeconde >= 1 && strSeconde <= 9) {
        strSeconde = "0" + strSeconde;
    }
    //时间日期字符串拼接
    var NewDate = date.getFullYear() + transverse + month + transverse + strDate + " " +
        strHour;
    //返回拼接字符串
    return NewDate;
}


